<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialov = true">添加vip用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- slot-scope="scope"  这一行所有的数据
      作用域插槽  slot-scope="scope"    prop="role_name"  不在生效
    -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 按钮1 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDia(scope.row.id)"> </el-button>
            <!-- 按钮2 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="showUserById(scope.row.id)"></el-button>
            <!--  按钮3-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加对话框 
  
   @close="addDieeee"  
   对话框 close方法，点击事件使用表单方法清除
-->
    <el-dialog title="添加" :visible.sync="addDialov" width="30%" @close="addDieeee">
      <!-- 主体 -->
      <!--  model 表单各个数据
  rules。验证规则
  -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormreg" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialov = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 蓝色按钮修改用户对话框 -->
    <!-- 
    :visible.sync表单打开关闭
   -->
    <el-dialog title="修改用户" :visible.sync="eaitDialogVisible" width="50%" @close="editFromClode">
      <!-- 表单主题 -->
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromref" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="eaitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFromuserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDiaClosed">
      <p>当前用户:{{ userinfo.username }}</p>
      <p>当前角色:{{ userinfo.role_name }}</p>
      <p>
        分配新角色：<el-select v-model="selectRoleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleinfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'users',
    data() {
      var checkAge = (rule, value, callback) => {
        const reeaak = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (reeaak.test(value)) {
          return callback()
        }
        callback(new Error('手机号不合法'))
      }
      var emailxx = (rule, value, callback) => {
        const reeaak = /\w+@\w+(\.\w+)+/
        if (reeaak.test(value)) {
          return callback()
        }
        callback(new Error('邮箱不合法'))
      }
      return {
        //  用户列表
        queryInfo: {
          query: '',
          // 当前页数
          pagenum: 1,
          // 每页显示多少条
          pagesize: 3
        },
        userlist: [],
        total: 0,
        // 添加对话框开启关闭
        addDialov: false,
        // 按钮修改的对话框
        eaitDialogVisible: false,
        // 分配角色
        setRoleDialogVisible: false,

        ruleForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 修改按钮表单里面的数据
        editFrom: {},
        rules: {
          name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              min: 6,
              max: 15,
              message: '长度在 6 到 15 个字符',
              trigger: 'blur'
            }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: emailxx, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkAge, trigger: 'blur' }
          ]
        },
        editFromRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: emailxx, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkAge, trigger: 'blur' }
          ]
        },
        //分配角色用户信息
        userinfo: '',
        // 角色的数据列表
        roleList: [],
        selectRoleId: ''
      }
    },
    created() {
      this.getUserList()
      // 页码打印
      //(this.queryInfo.query)
      //(this.queryInfo.pagenum)
      //(this.queryInfo.pagesize)
    },
    methods: {
      async getUserList() {
        const { data: res } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.error('用户列表失败')
        }
        this.userlist = res.data.users
        this.total = res.data.total
        //(res)
      },
      // 监听  pagesize
      handleSizeChange(neSize) {
        //(neSize)
        this.queryInfo.pagesize = neSize
        this.getUserList()
      },
      //  element 页码值
      handleCurrentChange(yema) {
        //(yema)
        this.queryInfo.pagenum = yema
        this.getUserList()
      },
      // 监听开关状态
      async userStateChanged(userinfo) {
        //(userinfo)
        const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        if (res.meta.status !== 200) {
          userinfo.mg_state = !userinfo.mg_state
          return this.$message.error('用户状态更新失败')
        }
        this.$message.success('用户状态更新成功')
      },
      // 监听添加对话框
      addDieeee() {
        this.$refs.ruleFormreg.resetFields()
      },
      // 确定的点击事件
      adduser() {
        this.$refs.ruleFormreg.validate(async (value) => {
          value
          if (!value) return
          const { data: res } = await this.$http.post('users', this.ruleForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败')
          }
          this.$message.success('添加成功')
          this.addDialov = false
          //  添加成功刷新成功
          this.getUserList()
        })
      },
      // 用户编辑对话框
      async showEditDia(id) {
        const { data: res } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败')
        }
        //  把当前一列中的表拿出来，整个传入到editFrom
        this.editFrom = res.data
        this.eaitDialogVisible = true
      },
      editFromClode() {
        this.$refs.editFromref.resetFields()
      },
      editFromuserInfo() {
        //  validate  预验证表单写的规则
        this.$refs.editFromref.validate(async (valid) => {
          valid
          if (!valid) return

          const { data: res } = await this.$http.put('users/' + this.editFrom.id, { email: this.editFrom.email, mobile: this.editFrom.mobile })
          if (res.meta.status !== 200) {
            return this.$message.error('更新失败')
          }

          this.eaitDialogVisible = false
          this.getUserList()
          this.$message.success('更新成功')
        })
      },
      // 删除用户整个
      async showUserById(id) {
        // 弹窗  confirm 确认返回字符串  cancel取消
        const confiresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => err)
        //(confiresult)

        if (confiresult !== 'confirm') {
          return this.$message.info('取消删除')
        }

        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.success('删除用户失败')
          // 删除成功重新调用数据
        }
        this.getUserList()
        this.$message.success('删除用户成功')
      },
      // 分配角色对话框
      async setRole(userinfo) {
        this.userinfo = userinfo
        this.setRoleDialogVisible = true
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.roleList = res.data
      },
      // 点击确定按钮
      async saveRoleinfo() {
        if (!this.setRoleDialogVisible) {
          return this.$message.error('请选择分配角色')
        }
        const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectRoleId })
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失败')
        }
        this.$message.success('获取角色列表成功')
        this.getUserList()
        this.setRoleDialogVisible = false
      },

      setRoleDiaClosed() {
        this.selectRoleId = ''
        this.userinfo = {}
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
  }
  .el-table {
    margin-top: 15px;
  }
  .el-pagination {
    margin-top: 15px;
  }
</style>
